package tgc.edu.xzy.custom;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import tgc.edu.xzy.entity.SysRole;
import tgc.edu.xzy.entity.SysUser;
import tgc.edu.xzy.repostory.SysUserRepository;

public class UserUtils {
	@Autowired
	private SysUserRepository userDAO;
	
	public SysUser getUser() {
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDetails.getUsername();
		SysUser user=userDAO.findByUsername(username);
		return user;
	}
	
	public boolean hasRole(String role) {
		List<SysRole> roles=getUser().getRoles();
		List<String> roleNames=new ArrayList<>();
		for (SysRole sysRole : roles) {
			roleNames.add(sysRole.getName());
		}
		return roleNames.contains(role);
	}
}